/*

WinClip

   Copyright (C) 2011, Gowtham (gowthamgowtham@gmail.com)

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

*/

#include "saveditemsdialog.h"
#include "ui_saveditemsdialog.h"

SavedItemsDialog::SavedItemsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SavedItemsDialog)
{
    ui->setupUi(this);

    inputDialog = new InputDialog(this);

    ui->listSavedItems->setSelectionMode(QAbstractItemView::SingleSelection);

    // Move and down functionality is not working! :(
    //ui->cmdMoveDown->setVisible(false);
    //ui->cmdMoveUp->setVisible(false);
}

SavedItemsDialog::~SavedItemsDialog()
{
    delete ui;
}

void SavedItemsDialog::cmdAddClicked()
{
    inputDialog->setInitialText("");
    if( inputDialog->exec() == QDialog::Accepted )
        ui->listSavedItems->addItem(inputDialog->getText());
}

void SavedItemsDialog::cmdRemoveClicked()
{
    int current = ui->listSavedItems->currentRow();
    if(current >= 0 )
        ui->listSavedItems->takeItem(current);
}

void SavedItemsDialog::prepare(const QStringList *list)
{
    ui->listSavedItems->clear();
    for( int i=0; i<list->size(); ++i )
        ui->listSavedItems->addItem(list->at(i));
}

void SavedItemsDialog::cmdEditClicked()
{
    int current = ui->listSavedItems->currentRow();

    if( current >= 0 )
    {
        inputDialog->setInitialText(ui->listSavedItems->item(current)->text());
        if( inputDialog->exec() == QDialog::Accepted )
        {
            ui->listSavedItems->item(current)->setText(inputDialog->getText());;
        }
    }
}

void SavedItemsDialog::cmdMoveUpClicked()
{
    swapItem(-1);
}

void SavedItemsDialog::swapItem(int updown)
{
    QListWidget *list = ui->listSavedItems;
    int current = list->currentRow();
    int newPosition = current + updown;
    if( newPosition < 0 || newPosition >= list->count() )
        return;

    QListWidgetItem *currentItem = list->takeItem(current);
    list->insertItem(newPosition, currentItem->text());
    delete currentItem;
    list->setCurrentRow(newPosition);
}

void SavedItemsDialog::cmdMoveDownClicked()
{
    swapItem(+1);
}

QStringList SavedItemsDialog::getSavedItems()
{
    QStringList list;

    for( int i=0; i<ui->listSavedItems->count(); ++i )
        list.append( ui->listSavedItems->item(i)->text() );

    return list;
}
